<?php

namespace Fn;
use \Codebar\html\barcode;

//use Think\Model;
class App extends Base {

    static function setTimeLimit($p = 30) {
        @set_time_limit($p);
    }

    static function setMemoryLimit($p = '130M') {
        @ini_set('memory_limit', $p);
    }

    static function errorReporting($p = 1) {
        @ini_set('display_errors', $p);
        @ini_set('log_errors', $p);
        error_reporting(E_ALL & ~E_NOTICE);
    }
	
    static function realRuntime() {
		@ob_end_clean();
		@ob_implicit_flush(1);
    }

    static function isDownload()
    {
      return i('post.X-REQUEST-WITH-X','no','trim')==='download-and-export';
    }

    static public function user($field = 'id', $userId = 'this') {
        $tmp = array(
            'id' => 'erp-user_id',
            'nickname' => 'erp-user_info.nickname',
            'account' => 'erp-user_info.account'
        );
        if ($userId === 'this' && (!empty($tmp[$field]))) {
            if ($field === 'id') {
                return intval(session($tmp[$field]));
            }
            return session($tmp[$field]);
        } else {
            $user = D('RbacUser')->getRbacUserById($userId);
            if (!empty($user)) {
                return $user[$field];
            }
        }
    }

    static public function sysUserId() {
        return 9999;
    }

    //static public function userId(){return 150;}
    static public function userId() {
        return intval(self::user('id'));
    }

    static public function userName() {
        return self::user('nickname');
    }

    static public function isSuperUser() {
        return false;
    }

    static public function cfg($key, $error = null) {
        static $cfg;
        if (is_null($cfg))
        $cfg = D('Config')->getCfg();

        return (isset($cfg[$key])) ? $cfg[$key] : $error;
    }

    /**
     * 对密码进行加密
     * @param string $password
     * @return string
     
    static public function getEncryptionPassword($password) {
        return md5($password);
    }*/
	
	/**
	* 对密码进行加密
	* @param string $password
	* @return string
	*/

	static public function getEncryptionPassword($password,$randKey=false) {
		if($randKey){
			$key = 'abcdefg!@#$%^&*';
			return md5(md5($password).md5($randKey).$key) .':'.$randKey;
		}else{
			return md5($password);
		}
	}

    /**
     *
     * @param $p 'ALL/JS/PHP/本地开发时请将这 IS_SANDBOX=true';
     */

    static public function getUserAuth($p = 'ALL') {
        $p = strtoupper($p);
        $auth = C('AUTH_ALIAS');
        $skip = trim(trim(C('SKIP_AUTH_USER')),',');

        $sandbox = C('IS_SANDBOX');
        $uid = self::userId();
        //筛选当前用户的权限
        if($uid>0 && MathExp::in( $uid , $skip )) $userAuth = array_keys($auth);
        else if(!empty($sandbox) && $sandbox) $userAuth = array_keys($auth);
        else $userAuth = session('erp-user_auth');

        $userAuth = array_flip($userAuth);
        $auth = array_intersect_key($auth, $userAuth);
        if ($p != 'ALL') {
            $field = $p === 'JS' ? 0 : 1;
            $r = array();
            foreach ($auth as $key => $value) {
                $r[] = empty($value[$field]) ? $key : $value[$field];
            }
			//添加老erp权限
			if(!in_array("#olderp", $r)){
				array_push($r, "#olderp");
			}
            return $r;
        }
        return $auth;
    }

    /**
     * 筛选当前用户的权限
     * @param unknown $auth
     * @param bool $type true:取消php权限
     * @return multitype:unknown
     */
    static public function authCheck($auth = '', $type = false) {
        if ($type === true) {
            return true;
        }

        if (strtolower(ACTION_NAME) === 'xpublic') {
            return true;
        }
        if (empty($auth)) {
            $auth = '#' . CONTROLLER_NAME . "." . ACTION_NAME;
        }

        $authList = self::getUserAuth('PHP');
        $authList = array_map('strtolower', $authList);
        return in_array(strtolower($auth), $authList);
    }

    /**
     * //$tpl='### AND uid'
     */
    static public function fiterByUser($str = '', $tpl = 'RIGHT') {
        $appendWhere = '(user_id=' . self::userId('id') . ')';

        if (empty($str))
            return $appendWhere;
        elseif ($tpl === 'RIGHT' || $tpl === 'LEFT') {
            $exp = '';
            if (trim($str) != '') {
                $str = '(' . $str . ')';
                $exp = ' AND ';
            }
            return $tpl === 'RIGHT' ? ($str . $exp . $appendWhere) : ($appendWhere . $exp . $str);
        } else {

            return str_replace(array('###', 'uid'), array($str, $appendWhere), $tpl);
        }
    }

    static function httpPath($p = '') {
        if(isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST'])){
            $mainFileName = '/' . basename(APP_MAIN_FILE);
            list($dir) = explode($mainFileName, trim($_SERVER['PHP_SELF']));
            $dir = trim($dir, '/');
            $root = 'http://' . $_SERVER['HTTP_HOST'] . "/$dir/";
        }else {
            $root = I('get.__httproot__','/','urldecode');
			if($root == "/"){
				$root = C("ERP_HTTP_ROOT");
			}
        }
        /* if(stristr($root,"127.0.0.1")||stristr($root,"192.168")||stristr($root,"localhost")){
          $root="http://hittime.net:8080/ebay_tool/";
          } */
        return $root . ltrim($p, '/');
    }

    /**
     * 网站根目录绝对路径
     * @param
     */
    static function appAbsoluteDir($p='') {
        $mainFileName = '/' . basename(APP_MAIN_FILE);
        list($dir) = explode($mainFileName, trim($_SERVER['PHP_SELF']));
        $dir = trim($dir, '/');
        /* if(empty($dir) && !$dir){
          $dir=PROJECT_DIR_NAME;
          } */
        $root = 'http://' . $_SERVER['HTTP_HOST'] . "/$dir/".$p;
        return $root;
    }

    /**
     * -----------------------------
     * 共公上传目录 目录不存在会自动创建
     * -----------------------------
     */
    static function uploadPath($file = '', $dir = '') {
        $path = rtrim(PROJECT_UPLOAD_PATH . trim($dir, '/'), '/') . '/';
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        return $path . $file;
    }

    /**
     * -----------------------------
     * 共公上传WEBURL
     * -----------------------------
     */
    static function uploadUrl($file, $dir) {
        $dir = trim($dir, '/');
        /* if(substr($dir,0,4)==='Bic/')
          return trim( str_replace(':::Bic/','http://img3.buyincoins.com/bicv2/',":::$dir") ,':').'/'.$file;
          else */
        return self::httpPath('Public/UploadFile/' . $dir . '/' . $file);
    }

    /**
     * -----------------------------
     * 统一按需取的 最合的大小的产品图 
     * -----------------------------
     */
    static function prodImg($img, $size = 'ORIGINAL') {
        $size = strtolower($size);
        $url = self::uploadUrl($img, '-----ProdImg/' . $size);
        list(, $url) = explode('-----ProdImg', $url);
		$root = C('EBAY_TOOL_HTTP_ROOT');
        return $root.'Public/UploadFile/ProdImg/' . $url;
    }

    /**
     * -----------------------------
     * 图片存储存地 目录不存在会自动创建
     * -----------------------------
     */
    static function prodImgPath($img, $size = 'ORIGINAL') {
        $size = strtolower($size);
        return self::uploadPath($img, 'ProdImg/' . $size);
    }

    /**
     * -----------------------------
     * 日志记录
     * -----------------------------
     */
    static function log($fileName, $content = '', $title = '') {
        $fileName = rtrim(LOG_PATH, '/') . '/Public-' . date('Y-m-d') . '/' . trim($fileName, '/');
        $path = dirname($fileName);
        if (!file_exists($path)) {
            $pPath = dirname($path);
            if (!file_exists($pPath)) {
                mkdir($pPath, 0777);
                chmod($pPath, 0777);
            }
            mkdir($path, 0777);
            chmod($path, 0777);
        }
        $s = "\n--------------------------------------" .
                "\n\t时间：" . time() . ' 时期:' . date('Y-m-d H:i') . $title .
                "\n--------------------------------------\n";
        file_put_contents($fileName, $s . var_export($content, true), FILE_APPEND);
    }

    /**
     * 数组排序
     * @param
     */
    static function arraySort(&$array, $by, $type = 'ASC', $returnRes = false) {
        foreach ($array as $k => $v) {
            $sort[$k] = is_null($v[$by]) ? 0 : $v[$by];
        }
        $type = (trim(strtoupper($type)) == 'ASC' || empty($type)) ? 'asort' : 'arsort';
        $type($sort);
        $r = array();
        foreach ($sort as $k => $v) {
            $r[] = $array[$k];
        }
        if ($returnRes)
            return $r;
        $array = $r;
    }
    
     /**
      * 返回两日期之间隔的天数
      * @param type $date_start
      * @param type $date_end
      * @return type
      */
    static function getDateDay($date_start,$date_end) {
        $Date_1 = $date_end;//"2009-07-08";
        $Date_2 = $date_start;//"2009-06-08";
        $Date_List_a1 = explode("-", $Date_1);
        $Date_List_a2 = explode("-", $Date_2);
        $d1 = mktime(0, 0, 0, $Date_List_a1[1], $Date_List_a1[2], $Date_List_a1[0]);

        $d2 = mktime(0, 0, 0, $Date_List_a2[1], $Date_List_a2[2], $Date_List_a2[0]);

        $Days = round(($d1 - $d2) / 3600 / 24);
        return $Days;
    }

    // 打印条形码地址
    static function jBacodeUrl($printId,$filetype = "PNG",$scale = 1,$font_family = 0, $thickness=30) {
        $barcodePlace = I("get.barcodePlace",1,"intval");
        $url = "html/image.php?filetype=$filetype&dpi=72&scale=$scale&rotation=0&font_family=$font_family&font_size=15&text=$printId&thickness=$thickness&checksum=&code=BCGcode128";
        if($barcodePlace==2){
          $url = "http://192.168.1.100/barcode/".$url;
        }else{
          $url = "Codebar/".$url;
        }
        return $url;
    }

    /**
     *   海外仓库公共列表
     * @return type
     */
    static function commonOwHouse() {
        return array(
            array(id => "15", name => "美国公共海外仓库", code => "OWUS",allow_country=>'')
        );
    }
    /**
     *   海外仓库列表
     * @return type
     */
    static function overseaWarehouse() {
        return array(
            array(id => "1", name => "递四方美西仓", code => "DRUS", country => "USA",allow_country=>array("US")),
            // array(id => "2", name => "E邮宝", code => "EUN", country => ""),
            array(id => "3", name => "万邑联澳洲仓", code => "WINITAU", country => "AUS"),
            array(id => "4", name => "出口易英国仓", code => "CK1UK", country => "GBR"),
            array(id => "5", name => "出口易美国仓", code => "CK1US", country => "USA",),
            array(id => "6", name => "奔腾英国仓", code => "BTUK", country => "GBR"),
            array(id => "7", name => "次方美国仓", code => "CFUS", country => "USA",allow_country=>array("US")),
			array(id => "9", name => "次方俄罗斯仓", code => "CFRU", country => "RUS",allow_country=>array("RU")),
            array(id => "8", name => "出口易德国仓", code => "CK1DE", country => "DEU"),
			array(id => "10",name => "法国仓", code => "FBC",country => "FRA"),
			array(id => "11",name => "肯尼亚仓", code => "FBK",country => "KEN"),
			array(id => "12",name => "FBA仓", code => "FBA",country => "USA",allow_country=>array("US",'UK','DE','FR','ES','IT','AU','CA')),
			array(id => "13", name => "递四方美东仓", code => "ERUS", country => "USA",allow_country=>array("US")),
			array(id => "14", name => "Winit美南仓", code => "SRUS", country => "USA",allow_country=>array("US")),
			array(id => "16", name => "SP印尼仓", code => "SPID", country => "ID",allow_country=>array("ID")),
			array(id => "17", name => "SP泰国海外仓", code => "SPTH", country => "TH",allow_country=>array("TH")),
			array(id => "18", name => "SP马来西亚海外仓", code => "SPMY", country => "MY",allow_country=>array("MY"))
            //array(id => "9", name => "出口易美国专线", code => "CKYUSTN", country => "USA"),
        );
    }
    /**
     * 国内仓库列表
     * @return type
     */
    static function othersWarehouse(){
        return array(
            array(id => "10", name => "东莞仓库", code => "DG", country => FALSE),
            array(id => "11", name => "东莞零库存", code => "DG-M", country => FALSE),
            array(id => "13", name => "义乌仓库", code => "YW", country => FALSE),
            array(id => "15", name => "义乌零库存", code => "YW-M", country => FALSE)
        );
    }

    // pdf面单的国家iso列表
    static function createPdfCountryList(){
        return array(
            "US",
            "UK",
            "RU",
            "GB",
            "CA"
        );
    }

    // pdf面单的国家iso列表
    static function returnFenJian($cn){
        $a = array(
            "RU"=>21,
            "US"=>22,
            "GB"=>23,
            "BR"=>24,
            "AU"=>25,
            "FR"=>26,
            "ES"=>27,
            "CA"=>28,
            "IL"=>29,
            "IT"=>30,
            "DE"=>31,
            "CL"=>32,
            "SE"=>33,
            "BY"=>34,
            "NO"=>35,
            "NL"=>36,
            "UA"=>37,
            "CH"=>38,
            "MX"=>39,
            "PL"=>40
        );
        if(isset($a[$cn])){
            return $a[$cn];
        }else{
            return "";
        }
    }

    //美国的邮编分类标示
    static function getCodeIdentByUS($code){
        $t = array(
            '0'=>'①(USJFKA)',
            '1'=>'①(USJFKA)',
            '2'=>'①(USJFKA)',
            '3'=>'①(USJFKA)',

            '4'=>'②(US)',
            '5'=>'②(US)',
            '6'=>'②(US)',

            '7'=>'③(USSFOA)',
            '8'=>'③(USSFOA)',
            '9'=>'④(USLAXA)',
            );
        $frist = substr($code, 0, 1 );
        if(!empty($t[$frist])){
            return $t[$frist];
        }
        return '';
    }



    //俄罗斯邮编分类标示
    static function getCodeIdentByRU($code){
        $t = array(
            '3'=>'(eka)',
            '4'=>'(eka)',

            '60'=>'(EKA)',
            '61'=>'(EKA)',
            '62'=>'(EKA)',

            '63'=>'(OVB)',
            '64'=>'(OVB)',
            '65'=>'(OVB)',
            '66'=>'(OVB)',
            '67'=>'(OVB)',

            '68'=>'(VVO)',
            '69'=>'(VVO)',

            ''=>'(MOW)'
            );
        $frist1 = substr($code, 0, 1);
        $frist2 = substr($code, 0, 2);

        if(!empty($t[$frist1])){
            return $t[$frist1];
        }
        if(!empty($t[$frist2])){
            return $t[$frist2];
        }
        return 'MOW';
    }

    //根据国家返回分区码
    static function getPartitionCode($con_iso,$field='partition_code'){
        /*
            partition_code=平常邮件分区号
            g_partition_code=挂号邮件分区号
            p_partition_code=平挂分拣码
        */
        $t = array(
            'RU'=>array('ch_name'=>'俄罗斯','en_name'=>'RUSSIA','partition_code'=>'7','g_partition_code'=>'11','p_partition_code'=>'21'),
            'US'=>array('ch_name'=>'美国','en_name'=>'AMERICA','partition_code'=>'4','g_partition_code'=>'5','p_partition_code'=>'22'),
            'GB'=>array('ch_name'=>'英国','en_name'=>'BRITAIN','partition_code'=>'8','g_partition_code'=>'5','p_partition_code'=>'23'),
            'BR'=>array('ch_name'=>'巴西','en_name'=>'BRAZIL','partition_code'=>'5','g_partition_code'=>'7','p_partition_code'=>'24'),
            'AU'=>array('ch_name'=>'澳大利亚','en_name'=>'AUSTRALIA','partition_code'=>'8','g_partition_code'=>'3','p_partition_code'=>'25'),
            'FR'=>array('ch_name'=>'法国','en_name'=>'FRANCE','partition_code'=>'4','g_partition_code'=>'5','p_partition_code'=>'26'),
            'ES'=>array('ch_name'=>'西班牙','en_name'=>'SPAIN','partition_code'=>'4','g_partition_code'=>'5','p_partition_code'=>'27'),
            'CA'=>array('ch_name'=>'加拿大','en_name'=>'CANADA','partition_code'=>'4','g_partition_code'=>'5','p_partition_code'=>'28'),
            'IL'=>array('ch_name'=>'以色列','en_name'=>'ISRAEL','partition_code'=>'8','g_partition_code'=>'3','p_partition_code'=>'29'),
            'IT'=>array('ch_name'=>'意大利','en_name'=>'ITALY','partition_code'=>'3','g_partition_code'=>'3','p_partition_code'=>'30'),
            'DE'=>array('ch_name'=>'德国','en_name'=>'GERMANY','partition_code'=>'8','g_partition_code'=>'3','p_partition_code'=>'21'),
            'CL'=>array('ch_name'=>'智利','en_name'=>'CHILE','partition_code'=>'6','g_partition_code'=>'8','p_partition_code'=>'32'),
            'SE'=>array('ch_name'=>'瑞典','en_name'=>'SWEDEN','partition_code'=>'8','g_partition_code'=>'3','p_partition_code'=>'33'),
            'BY'=>array('ch_name'=>'白俄罗斯','en_name'=>'BELARUS','partition_code'=>'4','g_partition_code'=>'5','p_partition_code'=>'34'),
            'NO'=>array('ch_name'=>'挪威','en_name'=>'NORWAY','partition_code'=>'8','g_partition_code'=>'3','p_partition_code'=>'35'),
            'NL'=>array('ch_name'=>'荷兰','en_name'=>'NETHERLAND','partition_code'=>'8','g_partition_code'=>'3','p_partition_code'=>'36'),
            'UA'=>array('ch_name'=>'乌克兰','en_name'=>'UKRAINE','partition_code'=>'4','g_partition_code'=>'5','p_partition_code'=>'37'),
            'CH'=>array('ch_name'=>'瑞士','en_name'=>'SWITZERLAND','partition_code'=>'3','g_partition_code'=>'3','p_partition_code'=>'38'),
            'MX'=>array('ch_name'=>'墨西哥','en_name'=>'MEXICO','partition_code'=>'5','g_partition_code'=>'7','p_partition_code'=>'39'),
            'PL'=>array('ch_name'=>'波兰','en_name'=>'POLAND','partition_code'=>'3','g_partition_code'=>'3','p_partition_code'=>'40'),
        );

        if(!empty($t[$con_iso])){
            return $t[$con_iso][$field];
        }
        return '';
    }



    // 本地可生成面单的运输方式
    static function createPdfShippintMethod(){
        return array(
                "YWSH_TN",
                "BJYW_TN",
                "SG",
                "SGPOST_TN",
                "JYRUISHI",
                "JYRUISHI_TN",
                "DGPT",
                "DG_TN",
                "SEPOST",
                "SEPOST_TN",
                "HZ",
                "HZ_TN",
                "MYPOST",
                "MYPOSTREG",
                "RUZX",
                "RUZX_TN",
                "WPT",
                "WPT_TN",
                "UNI",
                "UNIAU",
				"LGS",
                'SEKO',
                'YWSEKO',
                "LGSYW",
				"EYB_FJXX",
                'LWPY',
                'LWGH_TN',
				'LGS_POSTAL',
				'FOB_TN',
                'FOBPT',
				'TEQ_TN',
				"TEQPY",
				'HLYT',
				'HLYT_TN',
				'JYHL_TN',
				'JYHL',
				'LWCT',
				'LWE',
				'SPLWE',
				'EUB_DGXX',
				'FJWISH',
				'FJWISH_TN',
				'JYOZT',
				'JYOZT_TN',
				'DBEPG_TN',
				'SPTW_TN',
                'SPTWYW_TN',
				'SPTWDP_TN',
                'SPTWDPYW_TN',
				'DGWISH',
				'DGWISH_TN',
				'BPOST',
				'SZWISH_TN',
				'SZWISH',
				'SLS',
                'SLSYW',
                'SLSPY',
                'SLSPYYW',
				'GZWISH',
				'GZWISH_TN',
				'ECRU_TN',
				'JYTRPY',
				'JYTR_TN',
				'FTWISH_TN',
				'FTWISHPY',
                'JYBPOST',
                'JYBPOST_TN',
                'SFPY',
                'SF_TN',
                'OSUS',
                'OSUSYW',
                /*'SLSBZPY',*/
            );
    }
    /**
     * 所有仓库列表
     * @return type
     */
    static function warehouse($code="All") {
        $warehouse = array_merge(self::overseaWarehouse(),self::othersWarehouse());
        $warehouse = array_merge($warehouse,self::commonOwHouse());
        $warehouse = Arr::neaten($warehouse,'name','code');
        return $code=="All"?$warehouse:$warehouse[$code];
    }
	
    //生成树
    static function createTree($data,$start=0,$relation='name,text',$other=array(),$sort = false, $pname = false){
    		list($id,$text) = explode(',',$relation);
    		$other = empty($other)? array() : (is_string($other)? explode(',',$other): $other);
    		$r = array();
    		$sortBy = $sortType = '';
    		if($sort!==false){
    			list($sortBy,$sortType) = explode(',',trim($sort).',');
    			$sortBy = trim($sortBy);
    		}
    		if(isset($data[$start]) && !empty($data[$start])){
    			$i = 0;
    			$otherKey = $other['/'] = isset($other['/'])? $other['/'] : '@other'; unset($other['/']);
    			foreach ($data[$start] as $k=>$v){
    				$ChildrenId = isset($v['id'])?$v['id']:$k;
    				$r[$i] = array('id'=>$v[$id],'text'=>$v[$text], 'cls'=>'tree-pointer-cls', 'leaf'=>true, 'pid'=>$pname);
				
    				if(!empty($other)){
    					$otherResult = array();
    					if(!empty($other)){
    						foreach ($other as $otherIndex){
    							$otherResult[$otherIndex]	= isset($v[$otherIndex])? $v[$otherIndex] : '';
    						}
    						if($otherKey ==='/'){$r[$i] = array_merge($r[$i],$otherResult);}
    						else{$r[$i][$otherKey] = $otherResult;}
    					}
    				}
    	
    				if($sortBy!==''){$r[$i]['SORT-KEY']=($v[$sortBy]);}
    				if(isset($data[$k]) && !empty($data[$k])){
    					unset($r[$i]['leaf']);
    					$r[$i]['children'] = self::createTree($data,$k,$relation,array_merge($other,array('/'=>$otherKey)),$sort, $v['name']);
    				}
    				$i++;
    			}
    		}	
    		if($sortBy!=='') $r = self::arraySort($r,'SORT-KEY',$sortType,true);
    		return $r;
    }

    static function getBarcodeData($text,$arg=array(),$code='code128'){
        static $barcode;
        $code = strtolower($code);
        $codeList = array('code128'=>'BCGcode128'/*....*/);
        if(!isset($codeList[$code])) exit('条码类型不存在');
        if(is_null($barcode)){
            include_once(__DIR__ . '/Barcode/CreateBarcode.php');
            $barcode = new \CreateBarcode($codeList[$code],TEMP_PATH);
            //$barcode = new \BarCode( 'BCGcode39',TEMP_PATH );
        }
        /*$cfg = array(
            "filetype"=>"png",//
            "dpi"=>72,
            "scale"=>1,
            "rotation"=>0,
            "font_family"=>'Arial.ttf',
            "font_size"=>15,
            "text"=>$content,
            "thickness"=>30,
            "checksum"=>"",
            "code"=>'BCGcode128',
            "start"=>""
        );*/
        return $barcode ->getImgData($text,$arg);
    }

    static function getMailCfg(){
        include_once(__DIR__ . '/PHPMailer/PHPMailer.php');
        $cfg = new \PHPMailer();
        return $cfg;
    }
    
    
    /*
     * 给代码加锁 这里是用的tp的S方法
     * $key : 键
     * $valu: 数据
     * $time: 加锁的周期 默认60*30 半个小时
     * */
    static public function addcodeLock($key,$value,$time=''){
        if(empty($time)){
            $time = 60*30;   //半个小时
        }
    
        S($key,$value,$time);
    }
    /*
     * 判断这个key的锁存在吗
     * return
     * */
    static public function isCodeLock($key){
        return S($key);
    }
    
    /*
     * 代码解锁
     * */
    static public function delCodeLock($key){
        S($key,null);
    }

    //ping ip
    static public function ping($ip,$times=4,$code = 'gb2312'){
        header("Content-Type: text/html; charset=$code");
        $info = array();
        if(!is_numeric($times) ||  $times-4<0){
            $times = 4;
        }
        if(PATH_SEPARATOR==':' || DIRECTORY_SEPARATOR=='/'){//linux
            exec("ping $ip -c $times",$info);
            if(count($info) < 9)
            {
                $info['error']='timeout';
            }
        }else{ //windows
            exec("ping $ip -n $times",$info);
            if (count($info) < 10){
                $info['error']='timeout';
            }
        }
        return $info;
    }

    //返回pdf v3版本渠道
    static public function getPdfV3(){
        return array('JYTRPY','JYTR_TN',/*'SLSBZPY',*/'SF_TN','SFPY','JYBPOST','JYBPOST_TN','FTWISH_TN','FTWISHPY','DGWISH','DGWISH-US','LWGH_TN','LWCT','LWCT-CA','SGPOST_TN','DGPT','DGPT-DE','DGPT-US','DG_TN','DG_TN-EUR','DG_TN-NZ','SLSPY-SG','SLS-SG','SLS-TH','SLS-ID','SLS-MY','SLS-PH','SLS-VN','SLSPYYW-SG','SLSYW-SG','SLSYW-TH','SLSYW-ID','SLSYW-MY','SLSYW-PH','SLSYW-VN','OSUS','OSUSYW','YWSEKO-NG','SEKO-NG');
    }

    static public function jsonDecode($str,$toArray=false){
        $r = json_decode($str,$toArray);
        if(is_null($r)){//nodejs修复json
            $tmpFile = rtrim(TEMP_PATH,'/').'/'.uniqid().mt_rand(1000,999999).'.tmp.json';
            file_put_contents($tmpFile,$str);
            exec('node '.__DIR__.'/scripts/json_repair.js '.$tmpFile,$output);
			$output = implode("\n",$output);
            if(file_exists($tmpFile)) unlink($tmpFile);
            
            $outputArr = explode('[##--CONTENT--##]',$output);
            if(!empty($outputArr) && count($outputArr)>1){
                list($output) = explode('[/##--CONTENT--##]',$outputArr[1].'[/##--CONTENT--##]');
                $r = json_decode($output,$toArray);
            }
        }
        return $r;
    }
	
	//获取用户所属办公地点（仓库）
	static public function getWarehousByUser($userId = false){
		if(!$userId){
			$userId = self::userId();
		}
		$regionType = D('hr_employee')->where(array(
			'user_id'=> array('eq', $userId)
		))->getField('employee_region_type');
		if(!$regionType) return '';
		return trim(strtoupper($regionType));
	}
	
	//获取指定仓库的捡货人user id 集合
	static public function getPickUserListByWarehouse($warehouse){
		if(!$warehouse) return array();
		$res = M('rbac_user')->field("
			rbac_user.id  
		")->join("
			left join hr_employee on hr_employee.user_id = rbac_user.id  
		")->where(array(
			'hr_employee.employee_department_group'=> array('eq','WC-PG'),
			'employee_region_type'=> array('eq', strtoupper($warehouse))
		))->select();
		$res = Arr::neaten($res,'id');
		$res = array_unique(array_filter($res));
		return $res;
	}

    static public function getUserListByWarehouse($warehouse){
        if(!$warehouse) return array();
        $res = M('rbac_user')->field("
			rbac_user.id
		")->join("
			left join hr_employee on hr_employee.user_id = rbac_user.id
		")->where(array(
            'employee_region_type'=> array('eq', strtoupper($warehouse))
        ))->select();
        $res = Arr::neaten($res,'id');
        $res = array_unique(array_filter($res));
        return $res;
    }
}